const qiniuUploader = require("./qiniuUploader");

// 弄个id用于标识上传任务，每次使用都++，应该不会重复吧
let countId = 1;

//图片选择
export const chooseImage = function(data) {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: data.count || 9, //默认9
			sizeType: data.sizeType || ['compressed', 'original'], // ['original', 'compressed'], 可以指定是原图还是压缩图，默认二者都有
			sourceType: data.sourceType || ['album', 'camera'], //从相册选择
			success: function(res) {
				console.log('chooseImage:', res)
				resolve(res.tempFiles);
			},
			fail: err => {
				reject(err);
			}
		});
	});
}
//视频选择
export const chooseVideo = function(data) {
	return new Promise((resolve, reject) => {
		uni.chooseVideo({
			sourceType: data.sourceType || ['album', 'camera'], //从相册选择
			compressed: data.compressed || false, //是否压缩所选的视频源文件，默认值为 true，需要压缩。
			maxDuration: data.maxDuration || 60, //拍摄视频最长拍摄时间，单位秒。最长支持 60 秒。
			camera: data.camera || 'back', //'front'、'back'，默认'back'
			success: function(res) {
				let tempFiles = [{
					path: res.tempFilePath
				}];
				// #ifdef APP-PLUS || H5 || MP-WEIXIN
				tempFiles[0].duration = res.duration;
				tempFiles[0].size = res.size;
				tempFiles[0].height = res.height;
				tempFiles[0].width = res.width;
				// #endif
				// #ifdef H5
				tempFiles[0].name = res.name;
				// #endif
				resolve(tempFiles);
			},
			fail: err => {
				reject(err);
			}
		});
	});
}
// 七牛云上传
export const qiniuUpload = async function(requestInfo, getQnToken) {
	let checkRes = qnCheckParams(requestInfo, getQnToken);
	if (checkRes) {
		throw checkRes;
	}

	let qnRes = await getQnToken();
	
	let result = await uploadFiles(requestInfo, qnRes);
	
	return result;
}

function qnCheckParams(requestInfo, getQnToken) {
	if (!Array.isArray(requestInfo.files)) {
		return {
			errMsg: "files 必须是数组类型",
			statusCode: 0
		}
	}
	if (!getQnToken) {
		return {
			errMsg: "请添加七牛云回调方法：getQnToken",
			statusCode: 0
		}
	}
	return false;
}
			
function uploadFiles(requestInfo, qnRes) {
	let taskList = [];
	requestInfo.files.forEach(e => {
		let item = {
			path: e.path,
			status: 0,
			id: countId++
		}
		let task = uploadTask(requestInfo, item, qnRes);
		taskList.push(task);
	})
	return Promise.all(taskList);
}

function uploadTask(requestInfo, item, qnRes) {
	// 交给七牛上传
	requestInfo.onBeforeUpdate && requestInfo.onBeforeUpdate(item);
	return new Promise((resolve, reject) => {
		qiniuUploader.upload(item.path, (res) => {
			let result = {
				...item,
				key: res.key,
				status: 1
			}
			requestInfo.onEachUpdate && requestInfo.onEachUpdate(result);
			resolve(result);
		}, (error) => {
			reject(error);
		}, {
			uptoken: qnRes.token, // 由其他程序生成七牛 uptoken
			region: qnRes.region || 'SCN', //地区
		}, (res) => {
			requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object.assign({}, item, res));
		});
	})
}

// 服务器URL上传
export const urlUpload = function(requestInfo, dataFactory) {
	// 本地文件上传去掉默认Content-Type
	if (requestInfo.header && requestInfo.header['Content-Type']) {
		delete requestInfo.header['Content-Type'];
	}
	// 本地文件上传去掉默认Content-Type
	if (requestInfo.header && requestInfo.header['content-type']) {
		delete requestInfo.header['content-type'];
	}
	if (Array.isArray(requestInfo.files)) {
		const taskList = []
		requestInfo.files.forEach(e => {
			// 上传前钩子
			console.log(e)
			const item = { 
				path: e.path,
				status: 0,
				id: countId++
			}
			requestInfo.onBeforeUpdate && requestInfo.onBeforeUpdate(item);
			const task = new Promise((resolve, reject) => {
				const config = {
					url: requestInfo.url,
					files: [{ 
						uri: e.path,
						name: requestInfo.name || "file"
					}],
					header: requestInfo.header, 	//加入请求头
					success: (response) => {
						// 上传成功钩子
						const res = JSON.parse(response.data)
						requestInfo.onEachUpdate && requestInfo.onEachUpdate({
							...item,
							key: res && res.data && res.data[0] || '',
							status: 1
						});
						resolve(response);
					},
					fail: (err) => {
						reject(err);
					}
				};
				if (requestInfo.data) {
					config.formData = requestInfo.data;
				}
				const uploadTask = uni.uploadFile(config);
			});
			taskList.push(task);
		})
		console.log(taskList)
		return Promise.all(taskList);
	} else {
		return Promise.reject({
			errMsg: "files 必须是数组类型",
			statusCode: 0
		});
	}
}
